const { asyncHandler } = require('../middleware/errorHandler');
const { success } = require('../utils/common');
const { sequelize } = require('../config/database');
const User = require('../models/User');
const Course = require('../models/Course');
const Order = require('../models/Order');
const CourseUser = require('../models/CourseUser');
const { Op } = require('sequelize');

class StatisticsController {
  /**
   * 获取总体统计数据
   */
  static getOverallStats = asyncHandler(async (req, res) => {
    const [
      totalUsers,
      totalCourses,
      totalOrders,
      totalRevenue
    ] = await Promise.all([
      User.count(),
      Course.count({ where: { status: 'published' } }),
      Order.count({ where: { status: 'paid' } }),
      Order.sum('pay_amount', { where: { status: 'paid' } })
    ]);

    // 获取最近7天的数据
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

    const [
      newUsers,
      newCourses,
      newOrders,
      newRevenue
    ] = await Promise.all([
      User.count({ where: { created_at: { [Op.gte]: sevenDaysAgo } } }),
      Course.count({ 
        where: { 
          status: 'published',
          created_at: { [Op.gte]: sevenDaysAgo }
        }
      }),
      Order.count({ 
        where: { 
          status: 'paid',
          created_at: { [Op.gte]: sevenDaysAgo }
        }
      }),
      Order.sum('pay_amount', { 
        where: { 
          status: 'paid',
          created_at: { [Op.gte]: sevenDaysAgo }
        }
      })
    ]);

    res.json(success({
      overall: {
        total_users: totalUsers,
        total_courses: totalCourses,
        total_orders: totalOrders,
        total_revenue: totalRevenue || 0
      },
      recent: {
        new_users: newUsers,
        new_courses: newCourses,
        new_orders: newOrders,
        new_revenue: newRevenue || 0
      }
    }, '获取成功'));
  });

  /**
   * 获取用户统计
   */
  static getUserStats = asyncHandler(async (req, res) => {
    const { days = 30 } = req.query;
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - parseInt(days));

    // 用户注册趋势
    const userStats = await User.findAll({
      attributes: [
        [sequelize.fn('DATE', sequelize.col('created_at')), 'date'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      where: {
        created_at: { [Op.gte]: startDate }
      },
      group: [sequelize.fn('DATE', sequelize.col('created_at'))],
      order: [[sequelize.fn('DATE', sequelize.col('created_at')), 'ASC']]
    });

    // 用户角色分布
    const roleStats = await User.findAll({
      attributes: [
        'role',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['role']
    });

    // 活跃用户数（最近7天有登录的用户）
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
    const activeUsers = await User.count({
      where: {
        last_login_time: { [Op.gte]: sevenDaysAgo }
      }
    });

    res.json(success({
      trend: userStats,
      role_distribution: roleStats,
      active_users: activeUsers
    }, '获取成功'));
  });

  /**
   * 获取课程统计
   */
  static getCourseStats = asyncHandler(async (req, res) => {
    const { days = 30 } = req.query;
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - parseInt(days));

    // 课程创建趋势
    const courseStats = await Course.findAll({
      attributes: [
        [sequelize.fn('DATE', sequelize.col('created_at')), 'date'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      where: {
        created_at: { [Op.gte]: startDate }
      },
      group: [sequelize.fn('DATE', sequelize.col('created_at'))],
      order: [[sequelize.fn('DATE', sequelize.col('created_at')), 'ASC']]
    });

    // 课程分类分布
    const categoryStats = await Course.findAll({
      attributes: [
        'category_id',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      where: { status: 'published' },
      group: ['category_id']
    });

    // 热门课程（按学生数排序）
    const popularCourses = await Course.findAll({
      attributes: ['id', 'title', 'students_count', 'price'],
      where: { status: 'published' },
      order: [['students_count', 'DESC']],
      limit: 10
    });

    res.json(success({
      trend: courseStats,
      category_distribution: categoryStats,
      popular_courses: popularCourses
    }, '获取成功'));
  });

  /**
   * 获取订单统计
   */
  static getOrderStats = asyncHandler(async (req, res) => {
    const { days = 30 } = req.query;
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - parseInt(days));

    // 订单趋势
    const orderStats = await Order.findAll({
      attributes: [
        [sequelize.fn('DATE', sequelize.col('created_at')), 'date'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'count'],
        [sequelize.fn('SUM', sequelize.col('pay_amount')), 'revenue']
      ],
      where: {
        created_at: { [Op.gte]: startDate },
        status: 'paid'
      },
      group: [sequelize.fn('DATE', sequelize.col('created_at'))],
      order: [[sequelize.fn('DATE', sequelize.col('created_at')), 'ASC']]
    });

    // 支付方式分布
    const paymentStats = await Order.findAll({
      attributes: [
        'pay_type',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count'],
        [sequelize.fn('SUM', sequelize.col('pay_amount')), 'revenue']
      ],
      where: { status: 'paid' },
      group: ['pay_type']
    });

    // 订单状态分布
    const statusStats = await Order.findAll({
      attributes: [
        'status',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['status']
    });

    res.json(success({
      trend: orderStats,
      payment_distribution: paymentStats,
      status_distribution: statusStats
    }, '获取成功'));
  });

  /**
   * 获取收入统计
   */
  static getRevenueStats = asyncHandler(async (req, res) => {
    const { days = 30 } = req.query;
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - parseInt(days));

    // 收入趋势
    const revenueStats = await Order.findAll({
      attributes: [
        [sequelize.fn('DATE', sequelize.col('pay_time')), 'date'],
        [sequelize.fn('SUM', sequelize.col('pay_amount')), 'revenue']
      ],
      where: {
        status: 'paid',
        pay_time: { [Op.gte]: startDate }
      },
      group: [sequelize.fn('DATE', sequelize.col('pay_time'))],
      order: [[sequelize.fn('DATE', sequelize.col('pay_time')), 'ASC']]
    });

    // 总收入
    const totalRevenue = await Order.sum('pay_amount', {
      where: { status: 'paid' }
    });

    // 今日收入
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const todayRevenue = await Order.sum('pay_amount', {
      where: {
        status: 'paid',
        pay_time: { [Op.gte]: today }
      }
    });

    // 本月收入
    const thisMonth = new Date();
    thisMonth.setDate(1);
    thisMonth.setHours(0, 0, 0, 0);
    const monthRevenue = await Order.sum('pay_amount', {
      where: {
        status: 'paid',
        pay_time: { [Op.gte]: thisMonth }
      }
    });

    res.json(success({
      trend: revenueStats,
      total_revenue: totalRevenue || 0,
      today_revenue: todayRevenue || 0,
      month_revenue: monthRevenue || 0
    }, '获取成功'));
  });

  /**
   * 获取学习统计
   */
  static getLearningStats = asyncHandler(async (req, res) => {
    // 学习进度统计
    const progressStats = await CourseUser.findAll({
      attributes: [
        [sequelize.fn('AVG', sequelize.col('progress')), 'avg_progress'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'total_enrollments'],
        [sequelize.fn('COUNT', sequelize.fn('CASE', {
          when: { progress: { [Op.gte]: 100 } },
          then: 1
        })), 'completed_courses']
      ]
    });

    // 最近学习的课程
    const recentLearning = await CourseUser.findAll({
      include: [
        {
          model: Course,
          attributes: ['id', 'title', 'cover']
        }
      ],
      where: {
        last_learn_time: { [Op.ne]: null }
      },
      order: [['last_learn_time', 'DESC']],
      limit: 10
    });

    // 学习时长统计（按天）
    const learningTimeStats = await CourseUser.findAll({
      attributes: [
        [sequelize.fn('DATE', sequelize.col('last_learn_time')), 'date'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'active_learners']
      ],
      where: {
        last_learn_time: { [Op.ne]: null }
      },
      group: [sequelize.fn('DATE', sequelize.col('last_learn_time'))],
      order: [[sequelize.fn('DATE', sequelize.col('last_learn_time')), 'DESC']],
      limit: 7
    });

    res.json(success({
      progress: progressStats[0] || {},
      recent_learning: recentLearning,
      learning_trend: learningTimeStats
    }, '获取成功'));
  });
}

module.exports = StatisticsController; 